package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.UserConstants;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuditPageDto;
import com.heima.model.admin.pojos.ApUserRealname;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.UserAuditMapper;
import com.heima.user.service.UserAuditService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
@Transactional
public class UserAuditServiceImpl extends ServiceImpl<UserAuditMapper, ApUserRealname> implements UserAuditService {
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * 分页条件查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult pageList(UserAuditPageDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.1 分页参数校验
        dto.checkParam();
        //2 分页参数校验
        IPage page = new Page(dto.getPage(), dto.getSize());
        //3 状态条件查询
        LambdaQueryWrapper<ApUserRealname> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dto.getStatus() != null, ApUserRealname::getStatus, dto.getStatus());
        //4 查询
        page(page, lqw);
        //5 封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        return result;
    }

    /**
     * 用户审核通过或驳回
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPassOrFail(AuthDto dto) {
        //1、参数校验
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、业务处理
        //2.1、根据拒绝理由来判断是否通过 todo null的话就是反的
        update(Wrappers.<ApUserRealname>lambdaUpdate().eq(ApUserRealname::getId, dto.getId())
                .set(ApUserRealname::getUpdatedTime, new Date())
                .set(dto.getMsg() != null, ApUserRealname::getReason, dto.getMsg())
                .set(ApUserRealname::getStatus, (dto.getMsg().equals("") ? UserConstants.PASS_AUDIT : UserConstants.FAIL_AUDIT)));
        //2.2、并且通过后，用户信息添加到用户信息表  异步调用
        if (StringUtils.isEmpty(dto.getMsg())) {
            //1、先在app实名认证表中得到实名全部信息（主要是为了得到userId）
            ApUserRealname apUserRealname = getById(dto.getId());
            //2、其次在用户表查出用户信息（为了账户和密码）
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, apUserRealname.getUserId()));
            //3、往kafka里发送消息 （apuser序列化json） 自媒体监听这个topic PASS_AUDIT_KAFKA
            kafkaTemplate.send(UserConstants.PASS_AUDIT_KAFKA, JSON.toJSONString(apUser));
        }
        //3、返回响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}